package com.qf.fmall2203.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2203.user.entity.Users;
import com.qf.fmall2203.user.service.impl.UsersServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UsersServiceImpl service;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        String username = (String) token.getPrincipal();

        //根据token中的用户提供给的身份信息，去数据库中查询该用户的密码
        Users user = getUserFromDB(username);


        if (user==null){
            throw new UnknownAccountException("用户名不存在");
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName());

        return simpleAuthenticationInfo;
    }

    private Users getUserFromDB(String username) {

        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();

        usersQueryWrapper.eq("username",username);

        Users one = service.getOne(usersQueryWrapper);

        return one;
    }
}
